#include "chatwindow.h"
#include<QDebug>
#include<QEvent>
#include<QMouseEvent>
#include<QResizeEvent>
#include<QCloseEvent>
#include<QMessageBox>
#include<QFile>
#include<QTextStream>
#include"testwidget.h"
ChatWindow::ChatWindow(QWidget *parent)
    : QWidget(parent)
{

    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 滚动区域
    QScrollArea *scrollArea = new QScrollArea;
    scrollArea->setWidgetResizable(true);

    QWidget *chatContent = new QWidget;
    chatLayout = new QVBoxLayout(chatContent);
    chatLayout->setAlignment(Qt::AlignTop); // 消息从上往下堆叠
    scrollArea->setWidget(chatContent);

    mainLayout->addWidget(scrollArea);

    // 底部输入框
    QHBoxLayout *inputLayout = new QHBoxLayout;
    input = new QLineEdit;
    QPushButton *sendBtn = new QPushButton("发送");
    QPushButton *testBtn = new QPushButton("测试Qt");
    testBtn->setStyleSheet("QPushButton{"
                           "background-color:skyblue;"
                           "font-size:20px;"
                           "}");
    QPushButton *writeBtn = new QPushButton("写文件");
    sendBtn->setShortcut(Qt::Key_Return);
    inputLayout->addWidget(input);
    inputLayout->addWidget(sendBtn);
    inputLayout->addWidget(writeBtn);
    inputLayout->addWidget(testBtn);
    mainLayout->addLayout(inputLayout);
    connect(sendBtn, &QPushButton::clicked, this, &ChatWindow::sendMessage);

    connect(testBtn, &QPushButton::clicked, this, &ChatWindow::showTestWidget);
    connect(writeBtn, &QPushButton::clicked, this, &ChatWindow::writeFile);
}

ChatWindow::~ChatWindow()
{
    TestWidget::release();
}

void ChatWindow::writeFile()
{
    QFile file("text.txt");
    if(!file.open(QIODevice::WriteOnly|QIODevice::Text)){
        qDebug()<<"无法打开文件~";
        return;
    }
    QTextStream out(&file);

    out<<"Hello,Qt!\n";
    for(int i=0;i<10;i++){
        out<<"第 "+QString::number(i+1)+" 行"<<"\n";
    }
    file.close();
}

void ChatWindow::showTestWidget()
{
    TestWidget::getInstance()->show();
}

void ChatWindow::sendMessage()
{
    QString text = input->text();
    if (text.isEmpty()) return;

    // 自己的消息
    chatLayout->addWidget(new ChatBubble("[jack]2025-09-01 12:22", ChatBubble::Myself,true));
    chatLayout->addWidget(new ChatBubble(text, ChatBubble::Myself,false));
    input->clear();

    // 模拟对方回复
    chatLayout->addWidget(new ChatBubble("[lucy]2025-09-02 12:22", ChatBubble::Other,true));
    chatLayout->addWidget(new ChatBubble("收到啦：" + text, ChatBubble::Other,false));
}
